package ch.escaflowne.mangalist;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class mangaliste_acitivity extends ListActivity
{
	Manga manga;
	Toast toast;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		drawUI();
		
		registerForContextMenu(getListView());
    }
    
	private final static int CONTEXT_MENU_DELETE = 0;
	private final static int CONTEXT_MENU_EDIT = 1;
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
	{
		if (v.getId()==getListView().getId())
		{
			menu.setHeaderTitle("Context menu");
			
			menu.add(Menu.NONE, CONTEXT_MENU_DELETE, 0, "Delete");
			menu.add(Menu.NONE, CONTEXT_MENU_EDIT, 1, "Edit");
		}
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
		Cursor c = manga.getMangaCursor();
		
		if (c.moveToPosition(info.position))
			switch (item.getItemId())
			{
			case CONTEXT_MENU_DELETE:
				int _id = c.getInt(Manga.GET_MANGA_ID);
				manga.removeManga(_id);
				
				toast = Toast.makeText(getApplicationContext(), "Deleting " + c.getString(Manga.GET_MANGA_TITLE) + " _id: " + _id, Toast.LENGTH_LONG);
				toast.show();
				
				drawUI();
				break;
				
			case CONTEXT_MENU_EDIT:
				Intent intent = new Intent(this, addNewManga.class);
				
				intent.putExtra(addNewManga.INTENT_PARAMETER_TYPE, addNewManga.INTENT_TYPE_EDIT_MANGA);
				intent.putExtra(addNewManga.INTENT_PARAMETER_TITLE, c.getString(Manga.GET_MANGA_TITLE));
				intent.putExtra(addNewManga.INTENT_PARAMETER_AUTOR, c.getString(Manga.GET_MANGA_AUTOR));
				intent.putExtra(addNewManga.INTENT_PARAMETER_VOLUMES, c.getString(Manga.GET_MANGA_VOLUMES));
				intent.putExtra(addNewManga.INTENT_PARAMTERE_EDIT_ID, c.getInt(Manga.GET_MANGA_ID));
				
				startActivityForResult(intent, ADD_MANGA_ID);
				
				break;
			}
		
		return super.onContextItemSelected(item);
	}
    
    private void drawUI()
    {
    	try
		{
			manga = new Manga(this);
			
			setTitle("Manga Liste     " + manga.getTotalVolumeCount() + " Bände in " + manga.getTotalMangaCount() + " Serien.");

			//manga.addManga("Yotsuba&!", "Azuma Kyohiko", 10);
			/*
			manga.deleteAll();		//recreate database
			//add test books
			manga.addManga("Yotsuba&!", "Azuma Kyohiko", 10);
			manga.addManga("Azumanga Daioh", "Azuma Kyohiko", 4);
			manga.addVolume("0123456789123", 1, 1);
			*/
			
			Cursor cursor = manga.getMangaCursor();
			cursor.moveToFirst();
//			toast = Toast.makeText(this, cursor.getColumnName(1), Toast.LENGTH_SHORT);
//			toast.show();
			startManagingCursor(cursor);
			
			final SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
					android.R.layout.two_line_list_item,
					cursor,
					new String[]{"title","autor"},
					new int[]	{android.R.id.text1,android.R.id.text2});
			setListAdapter(sca);
			
		}
		catch (Exception e)
		{
			Log.w("SQL Exception", e.toString());
			toast = Toast.makeText(getApplicationContext(), "SQL Exception : " + e.toString(), Toast.LENGTH_LONG);
			toast.show();
		}
    }
    
    private void showMangaInformation(int _id)
    {
    	Intent intent = new Intent(this, showMangaInformation.class);
    	intent.putExtra("MANGA_ID", _id);
    	startActivity(intent);
    }
    
    private static final int SCAN_BARCODE_ID	= 0;
    private static final int ADD_MANGA_ID		= 1;
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	menu.add(0, SCAN_BARCODE_ID, Menu.NONE, "Scan Barcode");
    	menu.add(0, ADD_MANGA_ID, Menu.NONE, "Add Title");
    	
    	return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch (item.getItemId())
    	{
    	case SCAN_BARCODE_ID:
    		scanBarcode();
    		break;
    		
    	case ADD_MANGA_ID:
    		/*
    		if (manga.addManga("Azumanga", "Azuma", 4))
    			drawUI();
    		else
    		{
    			toast = Toast.makeText(this, "Title already in library", Toast.LENGTH_SHORT);
    			toast.show();
    		}
    		break;
    		*/
    		Intent intent = new Intent(this, addNewManga.class);
    		startActivityForResult(intent, INTENT_NR_ADD_MANGA);
    		
    	default:
    	}
    	
		return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id)
    {
    	super.onListItemClick(l, v, position, id);
    	
    	showMangaInformation((int)id);
    }
    
    private static final int INTENT_NR_SCAN_BARCODE = 0;
    private static final int INTENT_NR_ADD_MANGA = 1;
    
    private void scanBarcode()
    {
    	/*
		Intent intent = new Intent("com.google.zxing.client.android.SCAN");
		intent.setPackage("com.google.zxing.client.android");
		//intent.putExtra("SCAN_MODE", "ONE_D_MODE");
		startActivityForResult(intent, INTENT_NR_SCAN_BARCODE);
		*/
    	
		AlertDialog ad = IntentIntegrator.initiateScan(this, "ZXing Barcode Scanner not installed", "Would you like to open the market to download the separate barcode reader?", "Yes", "No", IntentIntegrator.PRODUCT_CODE_TYPES);
		if (ad != null)
			ad.show();
    }
    
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent)
	{
		Toast toast;
		switch (requestCode)
		{
		case INTENT_NR_SCAN_BARCODE:
			switch (resultCode)
			{
			case RESULT_OK:
				String isbn = intent.getStringExtra("SCAN_RESULT");
				//String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
				// Handle successful scan
				
				if (manga.findMangabyISBN(isbn) == -1)
				{	//nicht vorhanden
					toast = Toast.makeText(getApplicationContext(), "ISBN Nr." + isbn + " nicht bekannt.", Toast.LENGTH_LONG);
				}
				else
				{	//vorhanden
					toast = Toast.makeText(getApplicationContext(), "ISBN Nr. " + isbn + " in " + manga.getTitlebyID(manga.findMangabyISBN(isbn)) + " gefunden.", Toast.LENGTH_LONG);
				}
				toast.show();
				break;
				
			case RESULT_CANCELED:
				// Handle cancel
				toast = Toast.makeText(getApplicationContext(), "Scan abgebrochen", Toast.LENGTH_SHORT);
				toast.show();
				break;
			}
			break;
			
		case INTENT_NR_ADD_MANGA:
			if (resultCode == RESULT_OK)
			{
				if (intent.hasExtra(addNewManga.INTENT_PARAMETER_TYPE))
					if (intent.getStringExtra(addNewManga.INTENT_PARAMETER_TYPE).compareTo(addNewManga.INTENT_TYPE_EDIT_MANGA) == 0)
					{	//Returns from edit text
						if(manga.editManga(
								intent.getIntExtra(addNewManga.INTENT_PARAMTERE_EDIT_ID, -1),
								intent.getStringExtra(addNewManga.INTENT_PARAMETER_TITLE),
								intent.getStringExtra(addNewManga.INTENT_PARAMETER_AUTOR),
								intent.getIntExtra(addNewManga.INTENT_PARAMETER_VOLUMES, -1)))
							toast = Toast.makeText(getApplicationContext(), "Alles IO", Toast.LENGTH_SHORT);
						else
							toast = Toast.makeText(getApplicationContext(), "Fehler beim Update", Toast.LENGTH_SHORT);
						toast.show();
						break;
					}
				manga.addManga(
						intent.getStringExtra(addNewManga.INTENT_PARAMETER_TITLE), 
						intent.getStringExtra(addNewManga.INTENT_PARAMETER_AUTOR), 
						intent.getIntExtra(addNewManga.INTENT_PARAMETER_VOLUMES, 1));
				toast = Toast.makeText(getApplicationContext(), "Added new title", Toast.LENGTH_SHORT);
				toast.show();
			}
			break;
			
		case IntentIntegrator.REQUEST_CODE:
			if (resultCode == RESULT_OK)
			{
				IntentResult ir = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
				String isbn = ir.getContents();
				if (manga.findMangabyISBN(isbn) == -1)
				{	//nicht vorhanden
					toast = Toast.makeText(getApplicationContext(), "ISBN Nr." + isbn + " nicht bekannt.", Toast.LENGTH_LONG);
				}
				else
				{	//vorhanden
					
					if (manga.getTitlebyID(manga.findMangabyISBN(isbn)) == null)
					{
						manga.removeVolume(isbn);
						break;
					}
					toast = Toast.makeText(getApplicationContext(), "ISBN Nr. " + isbn + " in " + manga.getTitlebyID(manga.findMangabyISBN(isbn)) + " gefunden.", Toast.LENGTH_LONG);
					
				}
				toast.show();
			}
			break;
		}
		drawUI();
	}
}
